﻿using System.Collections.Generic;
using System.Linq;
using Dispatcher.Extensions;
using Dispatcher.Helpers;
using Dispatcher.ViewModels.Base;
using Repository;

namespace Dispatcher.ViewModels
{
    /// <summary>
    /// Generic Tree View Model
    /// </summary>
    internal class ObjectContextTreeViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectContextTreeViewModel"/> class.
        /// </summary>
        /// <param name="modelContainer">The model container.</param>
        public ObjectContextTreeViewModel(ModelContainer modelContainer)
        {
            EntitySetNames = new List<string>();
            EntitySetsWithViewModels = new Dictionary<string, ViewModelBase>();

            foreach (var entitySet in modelContainer.GetObjectSets())
            {
                EntitySetNames.Add(entitySet.ElementType.Name);
                var viewModel = ViewModelFactory.CreateObjectSetViewModel(entitySet.ElementType, modelContainer);
                EntitySetsWithViewModels.Add(entitySet.ElementType.Name, viewModel);
            }
        }

        /// <summary>
        /// Gets or sets the entity sets.
        /// </summary>
        /// <value>
        /// The entity sets.
        /// </value>
        public List<IQueryable> EntitySets { get; set; }

        /// <summary>
        /// Gets or sets the entity sets.
        /// </summary>
        /// <value>
        /// The entity sets.
        /// </value>
        public List<string> EntitySetNames { get; set; }

        /// <summary>
        /// Gets or sets the selected entity set.
        /// </summary>
        /// <value>
        /// The selected entity set.
        /// </value>
        public string SelectedEntitySetName
        {
            get
            {
                return Get(() => SelectedEntitySetName);
            }

            set
            {
                Set(() => SelectedEntitySetName, value);
                if (EntitySetsWithViewModels.ContainsKey(value))
                {
                    TreeViewModel = EntitySetsWithViewModels[value];
                }
            }
        }

        /// <summary>
        /// Gets or sets the generic tree view model.
        /// </summary>
        /// <value>
        /// The generic tree view model.
        /// </value>
        public ViewModelBase TreeViewModel
        {
            get { return Get(() => TreeViewModel); }
            set { Set(() => TreeViewModel, value); }
        }

        /// <summary>
        /// Gets or sets the entity sets with view models.
        /// </summary>
        /// <value>
        /// The entity sets with view models.
        /// </value>
        private Dictionary<string, ViewModelBase> EntitySetsWithViewModels { get; set; }
    }
}
